﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using DTO;
using DAL;
using DTO.InnerException;
using BLL.Util;
using System.Web.Security;

namespace BLL
{
    public class AccountBLL
    {
        /// <summary>
        /// 用户登录，如果用户信息异常与用户不存在会抛出相应异常
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool Login(string email, string password)
        {
            AccountDAL dal = new AccountDAL();
            password = Util.Security.Encrypt(password);//密码加密处理
            var table = dal.GetEntityByEmailAndPassword(email, password);
            if (table.Rows.Count>1)
            {
                throw new AccountErrorException();
            }
            else if (table.Rows.Count==0)
            {
                throw new NoAccountException();
            }
            else
            {
                Account entity = new Account() { Email = email, Password = password };
                entity.ID = int.Parse(table.Rows[0]["AID"].ToString());
                entity.AccountName = table.Rows[0]["account"].ToString();
                
                CacheHelper.CacheAddAccount(entity);//缓存
                FormsAuthentication.SetAuthCookie(entity.ID.ToString(), false);
                FormsAuthentication.RedirectFromLoginPage(entity.ID.ToString(), false);

                //自动记账
                var autolist = AutoSettingBLL.GetAutoSettingByAID(entity.ID);
                foreach (var auto in autolist)
                {
                    RecordBLL.AutoRecord(auto);
                }
                return true;
            }
        }
        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <param name="accountName"></param>
        /// <returns></returns>
        public static Account Register(string email, string password, string accountName)
        {
            password = Util.Security.Encrypt(password);//密码加密处理
            Account account = new Account();
            account.AccountName = accountName;
            account.Email = email;
            account.Password = password;
            
            AccountDAL dal = new AccountDAL();
            dal.Insert(account);
            return account;

        }

        internal static Account GetAccount(string accountID)
        {
            AccountDAL dal = new AccountDAL();
            return dal.GetEntityById(accountID);
        }
        
    }
}
